/**
 * Created by Wind on 2017/10/13.
 */
/**
 * List of tab names.
 * @private
 */

function get_board() {  //获取当前连接板子的类型
  var url = "http://" + window.location.host + '/select_board/';
  var method = "GET";
  var async = true;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (request.readyState != 4) {
      return;
    }
    var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
    if (status == 200) {
      var body = request.responseText.split(";");
      var board=body[0];
      var board_name=body[1];
      var a_list = $("li.board").find("a");
      for (var i = 0; i < a_list.length; i++) {
        var value = a_list[i].getAttribute('value');
        var cur_name=$(a_list[i]).parent('li').find("a").text();
        if (value == board && cur_name==board_name) {
          $(a_list[i]).parent('li').find("i").css("display", "block");
          window.board_name=board_name;
        }
        else {
          $(a_list[i]).parent('li').find("i").css("display", "none");
        }
      }
    }
  };
  request.open(method, url, async);
  request.send();
}

/**
 * Initialize Blockly.  Called on page load.
 */
var workspace = null;

function start() {

  // Setup blocks
  // Parse the URL arguments.
  var match = location.search.match(/dir=([^&]+)/);
  var rtl = match && match[1] == 'rtl';
  //document.forms.options.elements.dir.selectedIndex = Number(rtl);
  var toolbox = toolboxXml();
  //document.forms.options.elements.toolbox.selectedIndex =
  //toolbox ? 1: 0;

  match = location.search.match(/side=([^&]+)/);

  var side = match ? match[1] : 'start';

  //document.forms.options.elements.side.value = side;

  //Create main workspace.
  workspace = Blockly.inject('content_blocks', {
    comments: false,
    disable: false,
    collapse: false,
    media: '../../../blockly/media/',
    readOnly: false,
    rtl: rtl,
    scrollbars: true,
    toolbox: toolbox,
    toolboxPosition: side == 'top' || side == 'start' ? 'start' : 'end',
    horizontalLayout: side == 'top' || side == 'bottom',
    //sounds: soundsEnabled,
    grid:
      {
        spacing: 20,
        length: 3,
        colour: '#ccc',
        snap: true
      },
    zoom: {
      controls: true,
      wheel: true,
      startScale: 0.72,
      maxScale: 4,
      minScale: 0.25,
      scaleSpeed: 1.1
    },
    colours: {
      fieldShadow: 'rgba(255, 255, 255, 10)',
      dragShadowOpacity: 0.6
    },
    trashcan: true
  });
  get_board();
  get_connect_type();
  window.setInterval(function () {
    check_connect_state();
  },1000);
  var loadInput = document.getElementById('load');
  loadInput.addEventListener('change', load, false);
  document.getElementById('fakeload').onclick = function () {
    loadInput.click();
  };

  $.ajax({
      url: "http://"+window.location.host+"/get_first_open/",
      type: "Get",
      dataType: "json",
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        // alert("error!" + errorThrown);

      },
      success: function (data) {
        // var parse_data=JSON.parse(data);
        var first_open=data['first_open'];
        if(first_open==0){
          load_default_example_project();
        }
      }
    });
  refresh_history();
  workspace.addChangeListener(block_defind_event);

}

function refresh_history() {
  //获取用户积木编辑历史记录
  var history=$('.history');
  history.html('');
  $.ajax({
        url: "http://"+window.location.host+"/get_all_xml_history/",
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          for(var i=0;i<data.length;i++){
            var li='<li> <a href="#" data-toggle="modal" data-target="#myModal03">'+data[i]+'</a><button data-toggle="modal" data-target="#myModal04" class="delete_his" his_name="'+data[i]+'">'+$.i18n.prop('js_delete')+'</button></li>';
            history.append(li);
            $('.history li a').click(function(){
                var fonts=$(this).html();
                var fontss="<span>"+fonts+"</span>";
                $('.hisp span').replaceWith(fontss);
                $('.deletehisp span').replaceWith(fontss);
            });

            $('.history li button').click(function(){
                var fonts=$(this).attr('his_name');
                var fontss="<span>"+fonts+"</span>";
                $('.deletehisp span').replaceWith(fontss);
            });
          }
          if(data.length==0){
            var li='<li> <a href="#" data-toggle="modal" data-target="#">'+$.i18n.prop('js_no_history')+'</a>';
            history.append(li);
          }

        }
      });
}

function select_port(ele) {
    var port=$(ele).attr('value');
    $.ajax({
        url: "http://"+window.location.host+"/post_select_port/",
        type: "Post",
        async: false,
        data: port,
        dataType: "text",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          var li_list=$('#connect_port_list').find('li');
          for(var i=0;i<li_list.length;i++){
            var tmp_port=$(li_list[i]).find('a').attr('value');
            if(tmp_port==port){
              $(li_list[i]).find('i').show();
            }else{
               $(li_list[i]).find('i').hide();
            }
          }
        }
      });
  }


$(document).ready(function () {
  $('.historyyes').click(function (e) {
    var history_name=$('.historyyes').parent().parent().children('p').children('span').text();
    $.ajax({
        url: "http://"+window.location.host+"/get_xml_history/?xml_name="+history_name,
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          var code=data['code']
          var block_xml=data['xml_data']
          var msg=data['msg']
          if(code==1){
            alert(msg)
          }
          else{
            if(block_xml!=""){
                     try {
                    var xml = Blockly.Xml.textToDom(block_xml);
                } catch (e) {
                    alert($.i18n.prop('js_load_project_error'));
                    return;
                }
                var count = Blockly.mainWorkspace.getAllBlocks().length;
                Blockly.mainWorkspace.clear();
                Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
                $("#project_name").css("display","none");
                }
          }
        }
      });

  });

  $('.deletehistoryyes').click(function(){
   // $('.history li:eq(0)').remove();
    var history_name=$('.deletehistoryyes').parent().parent().children('p').children('span').text();
    var li_list=$('.history li');
    for(var i=0;i<li_list.length;i++){
      var li=li_list[i];
      var xml_name=$(li).children('a').text();
      if(history_name==xml_name){
        $.ajax({
        url: "http://"+window.location.host+"/delete_xml_history/?xml_name="+history_name,
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
           var code=data['code'];
          var msg=data['msg'];
          if(code==1){
            alert(msg)
          }
          else {
             li.remove();
          }
        }
      });
      }
    }
});



  $('#port_all').mouseover(function (ele) {
    $('#connect_port_list').empty();

    $.ajax({
        url: "http://"+window.location.host+"/get_all_port/",
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          var com_list=data['com_list'];
          var current_port=data['current_port'];

          for(var i=0;i<com_list.length;i++){
            if(com_list[i]==current_port){
              var sub_ele='<li class="board-port"><i class="glyphicon glyphicon-ok" style="display: block"></i><a href="javascript:void(0)" value="'+com_list[i]+'" onclick="select_port(this)">'+com_list[i]+'</a></li>'
            }else{
              var sub_ele='<li class="board-port"><i class="glyphicon glyphicon-ok" style="display: none"></i><a href="javascript:void(0)" value="'+com_list[i]+'" onclick="select_port(this)">'+com_list[i]+'</a></li>'
            }

            $('#connect_port_list').append(sub_ele);
          }
        }
      });

    });



  $.ajax({
        url: "http://"+window.location.host+"/get_arduino_control_mode/",
        type: "Get",
        async: false,
        dataType: "text",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          // var parse_data=JSON.parse(data);
            $('.arduino-control-mode').find('i').hide();
            var a_list=$('.arduino-control-mode');
            for(var i=0;i<a_list.length;i++){
              var value=$(a_list[i]).find('a').attr('value');
              if(value==data){
                $(a_list[i]).find('i').show();
                if(data=='0'){
                   $('#blockly_mode').text($.i18n.prop('js_offline_mode'));
                   $('.character_start').css('pointer-events','none');
                   $('.character_start').find('img').attr('src','img/run_blockly_none.png');
                   $('#character_reset').css('pointer-events','none');
                   $('#character_reset').find('img').attr('src','img/stop_blockly_none.png');
                   window.online_data_obj.set_start_state(false);

                }else{
                  $('#blockly_mode').text($.i18n.prop('js_online_mode'));
                  $('#arduino_upload_sketch').css('pointer-events','none');
                  $('#arduino_upload_sketch').css('color','#999');
                  $('#arduino_reset_sketch').css('pointer-events','none');
                  $('#arduino_reset_sketch').css('color','#999');
                   window.online_data_obj.set_start_state(true);

                }

              }
            }
        }
      });


});



function getToolboxElement() {
  var match = location.search.match(/toolbox=([^&]+)/);
  return document.getElementById('toolbox-' + (match ? match[1] : 'simple'));
}

function check_connect_state(){ //检测板子的连接状态
  var connect_type="0";

  var a_list = $("li.board-connect").find("a");
  for (var i = 0; i < a_list.length; i++) {
    var value = a_list[i].getAttribute('value');
    var qtype=$(a_list[i]).parent('li').find("i").css("display");
    if(qtype=="block"){
      connect_type=value
    }
  }

  var url = "http://" + window.location.host + '/port_connect_status/?connect_type='+connect_type;
  var method = "GET";
  var async = true;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (request.readyState != 4) {
      return;
    }
    var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
    if (status == 200) {
      var body = request.responseText;

      window.port_connect_status=body;
      if(body=="1"){
        if($(".connect_state").attr("title")!=$.i18n.prop('js_mrc_connect_state_success')){
          $(".connect_state").attr("src","/blockly/apps/blocklyduino/img/lv.png");
          $(".connect_state").attr("title",$.i18n.prop('js_mrc_connect_state_success'))
        }
      }
      else{
        if($(".connect_state").attr("title")!=$.i18n.prop('js_mrc_connect_state_error')){
          $(".connect_state").attr("src","/blockly/apps/blocklyduino/img/hong.png");
          $(".connect_state").attr("title",$.i18n.prop('js_mrc_connect_state_error'));
        }
      }
    }
    else{
      if($(".connect_state").attr("title")!=$.i18n.prop('js_mrc_connect_state_error')){
          $(".connect_state").attr("src","/blockly/apps/blocklyduino/img/hong.png");
          $(".connect_state").attr("title",$.i18n.prop('js_mrc_connect_state_error'));
        }
    }
  };
  request.open(method, url, async);
  request.send();
}

function get_connect_type() {   //换取板子上一次连接方式
  var url = "http://" + window.location.host + '/get_connect_type/';
  var method = "GET";
  var async = true;
  var request = new XMLHttpRequest();
  request.onreadystatechange = function () {
    if (request.readyState != 4) {
      return;
    }
    var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
    if (status == 200) {
      var body = request.responseText;
      var state=body.split(";")[0];
      var ip="";
      if(body.split(";").length>1) {
        ip = body.split(";");
      }
      var a_list = $("li.board-connect").find("a");
      for (var i = 0; i < a_list.length; i++) {
        var value = a_list[i].getAttribute('value');
        if (value == state) {
          $(a_list[i]).parent('li').find("i").css("display", "block");
          if(value=="2"){
            $(a_list[i]).text($.i18n.prop('js_wifi_connection'))
          }
        }
        else {
          $(a_list[i]).parent('li').find("i").css("display", "none");
        }
      }
    }
  };
  request.open(method, url, async);
  request.send();
}


  function select_board_connect_type(el) {
    var connect = el.getAttribute("value");
    var parent_el = $(el).parent("li");
    var ul_parent_el = $(el).parent("li").parent("ul");
    post_board_connect_type(connect, function (status, errorInfo) {
      if (status == 200) {
        ul_parent_el.find("i").css("display", "none");
        parent_el.find("i").css("display", "block");
        alert($.i18n.prop('js_choose_connect_success'));
      } else {
        alert($.i18n.prop('js_choose_connect_error') + errorInfo);
      }
    });
  }

  function post_board_connect_type(code, callback) {

    var url = "http://" + window.location.host + '/select_board_connect_type/';
    var method = "POST";

// You REALLY want async = true.
// Otherwise, it'll block ALL execution waiting for server response.
    var async = true;

    var request = new XMLHttpRequest();


    request.onreadystatechange = function () {
      if (request.readyState != 4) {
        return;
      }
      var status = parseInt(request.status); // HTTP response status, e.g., 200 for "200 OK"
      var errorInfo = null;
      switch (status) {
        case 200:
          break;
        case 0:
          errorInfo = "code 0\n\n"+$.i18n.prop('js_sever_code_0');
          break;
        case 400:
          errorInfo = "code 400\n\n"+$.i18n.prop('js_sever_code_400');
          break;
        case 500:
          errorInfo = "code 500\n\n"+$.i18n.prop('js_sever_code_500');
          break;
        case 501:
          errorInfo = "code 501\n\n"+$.i18n.prop('js_sever_code_500');
          break;
        default:
          errorInfo = "code " + status + "\n\n"+$.i18n.prop('js_sever_code_default');
          break;
      }
      ;

      callback(status, errorInfo);
    };

    request.open(method, url, async);
    request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    request.send(code);
  }




  function arduino_control_mode(ele) {
    var mode=ele.getAttribute("value");
    if(mode=="0"){
      $.ajax({
        url: "http://"+window.location.host+"/post_arduino_control_mode/",
        type: "Post",
        async: false,
        data: mode,
        dataType: "text",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {

        }
      });

      new QWebChannel(qt.webChannelTransport, function (channel) {
          window.handler = channel.objects.handler;
          window.handler.closeServer();
      });

      location.href='/';
    }
    else{

      var connect_state=window.port_connect_status;
      if(connect_state=='1'){   //Arduino板子是否在连接状态
        $.ajax({
        url: "http://"+window.location.host+"/post_arduino_control_mode/",
        type: "Post",
        async: false,
        data: mode,
        dataType: "text",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {

        }
      });

      var tmp_bockly_ip=null;
      var tmp_bockly_port=null;
      $.ajax({
            url: "http://"+window.location.host+"/get_bockly_ip_port/",
            type: "Get",
            async: false,
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              alert("error!" + errorThrown);

            },
            success: function (data) {
              // var parse_data=JSON.parse(data);
              tmp_bockly_ip=data['ip'];
              tmp_bockly_port=data['port'];
            }
          });



        new QWebChannel(qt.webChannelTransport, function (channel) {
          window.handler = channel.objects.handler;
          window.handler.run_websocket();
      });

      function change_online_mode() {
          var state=null;
          var message=null;
          $.ajax({
                  url: "http://"+tmp_bockly_ip+':'+tmp_bockly_port+"/get_board_init_success/",
                  type: "Get",
                  async: false,
                  dataType: "json",
                  error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // alert("error!" + errorThrown);
                  },
                  success: function (data) {
                      state=data['state'];
                      var message_id=data['message'];
                      message=$.i18n.prop(message_id)
                  }
                });
          if(state==1 || state==2){
              alert(message);
          }
          else if(state==3){
            location.href='/';
          }
          else if(state==0){
            $('#blockly_mode').text(message);
          }
        }

      function websocket_change_online_mode() {
        var state=null;
          var message=null;
        try{
          var ws=new WebSocket('ws://'+tmp_bockly_ip+':'+tmp_bockly_port+'/get_board_init_success');
          ws.onopen=function (event) {
             ws.send("start")

          };
          ws.onmessage = function(evt) {//绑定收到消息事件
          　　var data=JSON.parse(evt.data)
             state=data['state'];
            var message_id=data['message'];
            message=$.i18n.prop(message_id)
           if(state==1 || state==2){
              alert(message);
          }
          else if(state==3){
            location.href='/';
          }
          else if(state==0){
            $('#blockly_mode').text(message);
          }
          };
          ws.onclose = function(evt) { //绑定关闭或断开连接事件
            // 　　alert("Connection closed.");
            };
        }
        catch(e) {
          alert(e);
        }
      }


      for(var i=0;i<10;i++){
        setTimeout(function () {
          websocket_change_online_mode()
        },500+500*i)
      }
      //   websocket_change_online_mode()
      }
      else{
        alert($.i18n.prop('js_bord_state_check'))
      }
    }
  }

  function add_wifi_address(ele) {
    var wifi=prompt($.i18n.prop('js_input_wifi'),'192.168.4.1:9090');
    if(wifi!=null && wifi!=''){
      var add_ele='<li class="board-wifi"><i class="glyphicon glyphicon-ok" style="display: none"></i><a href="javascript:void(0)" value="'+wifi+'" onclick="select_wifi_address(this)">'+wifi+'</a></li>';
      $(ele).parent().before(add_ele);
    }

  }

  function select_wifi_address(ele) {
    var wifi=$(ele).attr('value');
    var parent_el = $(ele).parent("li");
    var ul_parent_el = $(ele).parent("li").parent("ul");
    $.ajax({
          url: "http://"+window.location.host+"/post_wifi_address/",
          type: "Post",
          async: false,
          data:wifi,
          dataType: "text",
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("error!" + errorThrown);
          },
          success: function (data) {
              ul_parent_el.find("i").css("display", "none");
              parent_el.find("i").css("display", "block");
          }
        });
  }


function get_wifi_info() {
    $('#connect_wifi_list').empty();
    $.ajax({
        url: "http://"+window.location.host+"/get_wifi_address_info/",
        type: "Get",
        async: false,
        dataType: "json",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);

        },
        success: function (data) {
          var wifi_list=data['wifi_list'];
          var current_wifi=data['current_wifi'];

          for(var i=0;i<wifi_list.length;i++){
            if(wifi_list[i]==current_wifi){
              var sub_ele='<li class="board-wifi"><i class="glyphicon glyphicon-ok" style="display: block"></i><a href="javascript:void(0)" value="'+wifi_list[i]+'" onclick="select_wifi_address(this)">'+wifi_list[i]+'</a></li>';
            }else{
              var sub_ele='<li class="board-wifi"><i class="glyphicon glyphicon-ok" style="display: none"></i><a href="javascript:void(0)" value="'+wifi_list[i]+'" onclick="select_wifi_address(this)">'+wifi_list[i]+'</a></li>';
            }

            $('#connect_wifi_list').append(sub_ele);
          }
          var add_ele='<li class="board-wifi"><i class="glyphicon glyphicon-ok" style="display:none"></i><a href="javascript:void(0)" value="add" onclick="add_wifi_address(this)"><span class="glyphicon glyphicon-plus" style="left: 45%"></span></a>';
          $('#connect_wifi_list').append(add_ele);
        }
      });

    }



  $(document).ready(function () {
    $('.character_start').mouseover(function (ele) {
      var image=$('.character_start').find('img');
      var src=$(image).attr('src');
      if(src!='img/run_blockly_bright.png'){
          $(image).attr('src','img/run_blockly_bright.png');
        }

    })
  });


  $(document).ready(function () {
    $('.character_start').mouseleave(function (ele) {
      var image=$('.character_start').find('img');
      var src=$(image).attr('src');
      var blockly_is_run=window.blockly_is_run;
      if(blockly_is_run==false || blockly_is_run==null){
        if(src!='img/run_blockly_dark.png'){
        $(image).attr('src','img/run_blockly_dark.png');
      }
      }
    })
  });


  $(document).ready(function () {
    $('#character_reset').mouseover(function (ele) {
      var image=$('#character_reset').find('img');
      var src=$(image).attr('src');
      if(src!='img/stop_blockly_bright.png'){
          $(image).attr('src','img/stop_blockly_bright.png');
        }

    })
  });


  $(document).ready(function () {
    $('#character_reset').mouseleave(function (ele) {
      var image=$('#character_reset').find('img');
      var src=$(image).attr('src');
      if(src!='img/stop_blockly_dark.png'){
        $(image).attr('src','img/stop_blockly_dark.png');
      }
    })
  });


  function upload_online_run_xml() {
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    var json_data=new Object();
    json_data["arduino_code"]='';
    json_data["xml"]=xmlText;
    json_data["block_count"]=workspace.getAllBlocks().length;
    json_data["user_edit"]=1;
    var new_code=JSON.stringify(json_data);
    $.ajax({
          url: "http://"+window.location.host+"/upload_online_run_xml/",
          type: "Post",
          async: false,
          data:new_code,
          dataType: "text",
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert("error!" + errorThrown);
          },
          success: function (data) {
          }
        });
  }

  $(document).ready(function () {
    $('#project_examples').empty();
    var file_list=[];
    $.ajax({
      url: "http://"+window.location.host+"/get_example_list/",
      type: "Get",
      async: false,
      dataType: "json",
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        // alert("error!" + errorThrown);
      },
      success: function (data) {
        // var parse_data=JSON.parse(data);
        file_list=data;
      }
    });
    for(var i=0;i<file_list.length;i++){
      var one_example='<li><a href="javascript:void(0)" onclick="get_example_project(this)">'+file_list[i]+'</a></li>';
      $('#project_examples').append(one_example);
    }
  });


  block_field_map={
    "inout_digital_pin":"d_pin_values",
    "inout_analog_pin":"a_pin_values",
    "customs_motor_m":"text_values"
    };


const_block_field_map={
    "green_servo_move":7,
    "white_servo_move":11,
    "blue_servo_move":8,
    "black_servo_move":13,
    "red_servo_move":4,
    "customs_servo_motor_two":"MT"
};

function check_include(item) {
    if(item in block_field_map){
        return true
    }else{
        return false
    }
}

function const_check_include(item) {
    if(item in const_block_field_map){
        return true
    }else{
        return false
    }
}

function get_field_value(key) {
    return block_field_map[key]
}


function get_const_field_value(key) {
    return const_block_field_map[key]
}

function block_defind_event(event) {
  console.log(event);
    if(event.type==Blockly.Events.BLOCK_CHANGE){
        var old_value=event.oldValue;
        var new_value=event.newValue;
        var block_obj=workspace.getBlockById(event.blockId);
        if(check_include(block_obj.type)){
            window.online_data_obj.remove_pin_mode(event.blockId);
            window.online_data_obj.set_pin_mode(event.blockId,new_value);
            // console.info(window.online_data_obj.get_pin_mode_map())

        }
    }
    if(event.type==Blockly.Events.BLOCK_CREATE){
        // var block_obj=workspace.getBlockById(event.blockId);
        // // var block_name=block_obj.type;
        // for(var i=0;i<block_obj.childBlocks_.length;i++){
        //     if(check_include(block_obj.childBlocks_[i].type)){
        //         var pin=block_obj.childBlocks_[i].getFieldValue(get_field_value(block_obj.childBlocks_[i].type));
        //         window.online_data_obj.set_pin_mode(block_obj.childBlocks_[i].id,pin);
        //         // console.info(window.online_data_obj.get_pin_mode_map())
        //     }
        // }
        //
        // if(const_check_include(block_obj.type)){
        //         window.online_data_obj.set_pin_mode(block_obj.id,get_const_field_value(block_obj.type));
        //         // console.info(window.online_data_obj.get_pin_mode_map())
        // }
        var all_blocks=workspace.getAllBlocks();
        for(var i=0;i<all_blocks.length;i++){
          if(check_include(all_blocks[i].type)){
                var pin=all_blocks[i].getFieldValue(get_field_value(all_blocks[i].type));
                window.online_data_obj.set_pin_mode(all_blocks[i].id,pin);
                // console.info(window.online_data_obj.get_pin_mode_map())
            }
            if(const_check_include(all_blocks[i].type)){
                window.online_data_obj.set_pin_mode(all_blocks[i].id,get_const_field_value(all_blocks[i].type));
                // console.info(window.online_data_obj.get_pin_mode_map())
        }
        }

    }
    if(event.type==Blockly.Events.BLOCK_DELETE){
        var ids=event.ids;
        for(var i=0;i<ids.length;i++){
                window.online_data_obj.remove_pin_mode(ids[i]);
                // console.info(window.online_data_obj.get_pin_mode_map())
        }
    }
}
